#!/usr/bin/env zx
import shell from 'shelljs'
import { $,question,chalk } from 'zx'
$.verbose = false // 消除额外的命令详细信息
let ProcessOutput = await $`git branch --show-current`
let branch = ProcessOutput.stdout.trim()  // 当前分支
let choicesList = ['yes','y','Y'] // 选择数组
let exec = shell.exec // 执行命令
try{
  if(branch === 'master'){
    erroLog('不可以操作master分支')
    exitFunc()
  }
  const pullResult =  exec('git pull')
  const { code } = pullResult
  if(code == 0){
    submit()
  }else{
    let answer = await question(greenLog('你的分支未链接远程，你需要推送此分支至远程并且提交吗？y/n '), { choices: choicesList })
    if( choicesList.includes(answer)){
      await $`git push --set-upstream origin ${branch}`
      await submit()
    }else{
      erroLog('你自己来吧')
      exitFunc()
    }
  }
  console.log('继续执行************')
}catch(error){
  erroLog(error,'进入错误')
}

// 提交流程
async function submit(){
  let message = process.argv[3] // message
  let commitId = process.argv[4]  // commitId
  let forcePush = 'git push -f' // 强推命令
  if(!message || message.trim() == ''){
    erroLog('请输入提交的message信息')
    exitFunc()
  }
  let pushCommand // 提交命令
  if(commitId){
    if(commitId.length == 40){
     await $`git reset ${commitId}`
     pushCommand = forcePush
    }else{
      erroLog('commitId格式不正确')
      exitFunc()
    }
  }else{
    pushCommand = 'git push'
  }
  if (exec('git add .').code !== 0) {
    erroLog('git add failed')
    exitFunc()
  }
  if (exec(`git commit -m "${message}"`).code !== 0) {
    erroLog('git commit failed')
    exitFunc()
  }
  if (exec(pushCommand).code !== 0) {
    erroLog(`${pushCommand} failed`)
    exitFunc()
  }else{
    let msg = pushCommand == forcePush ? '合并提交记录成功': '提交成功'
    greenLog(msg)
    if(pushCommand == forcePush){ 
      if(exec(`git rebase master`).code !== 0){
          exec('git rebase --abort')
          erroLog('rebase失败,你需要自己git rebase master了')
      }else{
        if(exec(pushCommand).code !== 0) {
          erroLog(`${pushCommand} failed`)
          exitFunc()
        }else{
          greenLog('git rebase master 成功')
        }
      }
    }
  }
  exitFunc() 
}

// 退出执行
function exitFunc(){
  process.exit(0)
}

// 打印主题色函数
function greenLog(log){
  console.log(chalk.green(log))
}
function erroLog(log){
  console.log(chalk.red(log))
}